<!--
 * @Author: lijilong
 * @Date: 2024-06-13 12:46:18
 * @LastEditors: lijilong lijilong@thwater.com
 * @LastEditTime: 2024-10-15 15:51:13
 * @Description: 
 * 
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
-->
<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '实验报告',
    enablePullDownRefresh: false,
    navigationStyle: 'custom',
  },
}
</route>
<template>
  <page-meta :root-font-size="setting.rootFontSize"></page-meta>
  <view>
    <view style="position: sticky; top: 0; z-index: 9999; width: 100%" class="task-custom">
      <wd-navbar :title="form.projectName || '实验报告'" :bordered="false" safeAreaInsetTop>
        <template #left>
          <wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
        </template>
      </wd-navbar>
    </view>
    <view class="scroll-container" :style="{ height: heightStyle }">
      <view class="left-container" :class="{ hide: !showCatalogues }" :style="{}">
        <view class="toggle" @click="toggleCatalogues">
          <text class="cuIcon-back"></text>
          <text>收起</text>
        </view>
        <scroll-view scrollY class="left" :style="{
          height: `calc(100vh - 80rpx - ${statusBar}px)`,
        }" :scroll-with-animation="true">
          <view class="item" :id="'reportView' + item.value" :class="{ active: currentNode === item.value }"
            v-for="(item, index) in catalogues" :key="index">
            <view class="item_text" :class="{ no_data: item.noData }" @click="onClickTab(item, index)">
              {{ item.name }}
            </view>
          </view>
        </scroll-view>
      </view>
      <scroll-view class="flex-1 scroll-view" :scroll-with-animation="true" scrollY @scroll="onViewScroll"
        :scroll-into-view="'reportView' + nodeNum">
        <view class="open" :class="{ show: showOpenMenu }" :style="{ top: 100 + 'px' }" @click.stop="toggleCatalogues"
          @touchstart="onTouchOpenMenu">
          <text class="cuIcon-right"></text>
        </view>
        <th-card id="reportView1" title="基础信息">
          <th-form labelWidth="100px">
            <th-form-item label="项目名称" v-if="form.petitionName">
              <text class="text">{{ form.petitionName }}</text>
            </th-form-item>

            <th-form-item label="需求产品名称" v-if="form.compoundFlag == 1">
              <wd-textarea disabled type="textarea" auto-height v-model="form.rdDemandEntityInvName" clearable
                style="width: 100%" no-border class="diabledStyle" placeholder=" "></wd-textarea>
            </th-form-item>
            <th-form-item label="需求产品规格" v-if="form.compoundFlag == 1">
              <wd-textarea disabled type="textarea" auto-height v-model="form.rdDemandEntityInvStd" clearable
                style="width: 100%" no-border class="diabledStyle" placeholder=" "></wd-textarea>
            </th-form-item>
            <th-form-item label="产品名称">
              <wd-textarea disabled type="textarea" auto-height v-model="form.invName" clearable style="width: 100%"
                no-border class="diabledStyle" placeholder=" "></wd-textarea>
              <!-- <text class="text">{{ form.invName }}</text> -->
            </th-form-item>
            <th-form-item label="产品规格">
              <wd-textarea disabled type="textarea" auto-height v-model="form.invStd" clearable style="width: 100%"
                no-border class="diabledStyle" placeholder=" "></wd-textarea>
              <!-- <text class="text">{{ form.invStd }}</text> -->
            </th-form-item>
            <th-form-item label="实验目的">
              <wd-textarea v-model="form.purpose" readonly auto-height placeholder=" " style="width: 100%" no-border
                class="diabledStyle"></wd-textarea>
              <!-- <text class="text">{{ form.purpose }}</text> -->
            </th-form-item>

            <th-form-item label="任务负责人">
              <view>
                <text class="text" v-for="(item, index) in form.projectHeadName" :key="index">
                  {{ index > 0 ? '，' : '' }}{{ item.userName }}
                </text>
              </view>
            </th-form-item>
            <template v-if="showMoreDemand">
              <th-form-item label="任务成员">
                <view>
                  <text class="text" v-for="(item, index) in form.rdProjectUserEntity" :key="index">
                    {{ index > 0 ? '，' : '' }}{{ item.userName }}
                  </text>
                </view>
              </th-form-item>
              <th-form-item label="报告编码">
                <text class="text">{{ form.ccode }}</text>
              </th-form-item>
              <th-form-item label="任务编码">
                <text class="text">{{ form.projectCode }}</text>
              </th-form-item>
              <th-form-item label="报告日期">
                <text class="text">{{ form.ddate }}</text>
              </th-form-item>
              <th-form-item label="需求描述">
                <wd-textarea v-model="form.description" disabled auto-height placeholder=" " style="width: 100%" no-border
                  class="diabledStyle"></wd-textarea>
                <!-- <text class="text"></text> -->
              </th-form-item>
              <!-- <th-form-item label="实验日期">
							<text class="text">{{ form.ddate }}</text>
						</th-form-item> -->
              <th-form-item label="反应方程式">
                <text class="text">
                  <image class="craft-row-img" :src="form.reactEquation" mode="scaleToFill"
                    @click="previewFileHandle(form.reactEquation)" />
                </text>
              </th-form-item>

              <view style="width: 100%">
                <view class="viewLabel"><text>反应装置</text></view>
                <view class="table-container">
                  <table class="analysis-table">
                    <tbody>
                      <tr>
                        <th>反应装置</th>
                        <th>用料规格</th>
                        <th>最大搅拌量</th>
                        <th>最小搅拌量</th>
                        <th>单位</th>
                      </tr>
                      <tr align="center" v-for="(item, index) in form.deviceList" :key="index">
                        <td>{{ item.name }}</td>
                        <td>{{ item.capacity }}</td>
                        <td>{{ item.maxValue }}</td>
                        <td>{{ item.minValue }}</td>
                        <td>{{ item.unit }}</td>
                      </tr>
                    </tbody>
                  </table>
                </view>
              </view>
            </template>
            <view class="exportModel" @click="showMoreDemand = !showMoreDemand">
              <text>{{ showMoreDemand ? '收起' : '展开' }}</text>
            </view>
          </th-form>

          <!-- <th-form labelWidth="100px">
						<th-form-item label="反应装置" class="viewTable">
							<view class="table-container">
								<table class="analysis-table">
									<tbody>
										<tr>
											<th>反应装置</th>
											<th>用料规格</th>
											<th>最大搅拌量</th>
											<th>最小搅拌量</th>
											<th>单位</th>
										</tr>
										<tr align="center" v-for="(  item, index  ) in form.deviceList" :key="index">
											<td>{{ item.name }}</td>
											<td>{{ item.capacity }}</td>
											<td>{{ item.maxValue }}</td>
											<td>{{ item.minValue }}</td>
											<td>{{ item.unit }}</td>
										</tr>
									</tbody>
								</table>
							</view>
						</th-form-item>
					</th-form> -->
        </th-card>
        <th-card id="reportView2" title="需求指标" v-if="form.rdDemandStandardEntity && form.rdDemandStandardEntity.length">
          <view class="table-container">
            <table class="analysis-table">
              <tbody>
                <tr>
                  <th>检验指标名称</th>
                  <th>U8指标</th>
                  <th>客户指标</th>
                  <th>检测值</th>
                  <th>描述</th>
                </tr>
                <tr align="center" v-for="(item, index) in form.rdDemandStandardEntity" :key="index">
                  <td>{{ item.standardName }}</td>
                  <td>{{ item.standardValue }}</td>
                  <td>{{ item.standardValuePm }}</td>
                  <td>{{ item.checkValue }}</td>
                  <td>{{ item.standardDesc }}</td>
                </tr>
              </tbody>
            </table>
          </view>
        </th-card>
        <th-card id="reportView3" title="用料及配比">
          <view class="table-container">
            <table class="analysis-table">
              <tbody>
                <tr>
                  <th style="width: 320rpx; min-width: 9.5rem">用料名称</th>
                  <th style="width: 280rpx; min-width: 280rpx">用料规格</th>
                  <th style="width: 280rpx; min-width: 380rpx">密度</th>
                  <th style="width: 280rpx; min-width: 180rpx">占比（%）</th>
                  <th style="width: 320rpx; min-width: 480rpx" v-if="form.compoundFlag != 1">
                    范围
                  </th>
                  <th style="width: 280rpx; min-width: 280rpx">计划用量</th>
                  <th style="width: 280rpx; min-width: 280rpx" v-if="form.compoundFlag != 1">
                    实际用量
                  </th>
                  <th style="width: 320rpx; min-width: 180rpx">单位</th>
                </tr>
                <tr align="center" v-for="(item, index) in materialList" :key="index">
                  <td>{{ item.invName }}</td>
                  <td>{{ item.invStd }}</td>
                  <td>{{ item.density }}</td>
                  <td>{{ item.proportion }}</td>
                  <td v-if="form.compoundFlag != 1">
                    <text>
                      {{
                        minPlanDosage(item.density, item.proportion, form.deviceList[0].minValue)
                      }}
                    </text>
                    ~
                    <text>
                      {{
                        maxPlanDosage(item.density, item.proportion, form.deviceList[0].maxValue)
                      }}
                    </text>
                  </td>
                  <td>{{ item.planNum }}</td>
                  <td v-if="form.compoundFlag != 1">{{ item.realNum }}</td>
                  <td>{{ item.unit }}</td>
                </tr>
                <block v-if="!materialList.length && form.compoundFlag == 1">
                  <tr align="center">
                    <td :colspan="6">暂无数据</td>
                  </tr>
                </block>
                <block v-else-if="!materialList.length && form.compoundFlag != 1">
                  <tr align="center">
                    <td :colspan="8">暂无数据</td>
                  </tr>
                </block>
                <tr align="center" v-if="form.compoundFlag == 1 && materialList.length">
                  <td>合计</td>
                  <td></td>
                  <td></td>
                  <td>{{ totalProportion(materialList) }}</td>
                  <td></td>
                  <td></td>
                </tr>
              </tbody>
            </table>
          </view>
        </th-card>
        <th-card title="用料产出" v-if="recordOutList && recordOutList.length">
          <view class="table-container">
            <table class="analysis-table">
              <tbody>
                <tr>
                  <th>物料名称</th>
                  <th>物料规格</th>
                  <th>数量</th>
                  <th>单位</th>
                </tr>
                <tr align="center" v-for="(item, index) in recordOutList" :key="index">
                  <td>{{ item.invName }}</td>
                  <td>{{ item.invStd }}</td>
                  <td>{{ item.dosage }}</td>
                  <td>{{ item.unit }}</td>
                </tr>
              </tbody>
            </table>
          </view>
        </th-card>
        <th-card id="reportView4" :title="!switchAction ? '实验过程记录' : '工艺流程'">
          <template v-slot:titleRight>
            <text @click="() => (switchAction = !switchAction)">
              <wd-icon name="translate-bold" size="22px"></wd-icon>
            </text>
          </template>
          <view v-show="!switchAction">
            <ExperimnetStepTablePreview :materialList="tableStepList" :record-id="form.pid" />
          </view>
          <view v-show="switchAction">
            <ExperimnetStepPreview :materialList="form.stepList" mode="record"
              @switchChange="switchAction = !switchAction" />
          </view>
        </th-card>
        <th-card id="reportView5" title="检验结论">
          <view class="table-container">
            <scroll-view scroll-x scroll-y class="th-table">
              <table class="analysis-table" v-if="middleCheckData.length">
                <thead class="sticky_top">
                  <tr>
                    <th colspan="9">中控检验报告</th>
                  </tr>
                  <tr>
                    <th>工序</th>
                    <th>报检次序</th>
                    <th>取样位置</th>
                    <th style="white-space: nowrap">取样时机描述</th>
                    <th>取样时机</th>
                    <th>分析手段</th>
                    <th>指标名称</th>
                    <th>实测值</th>
                    <th>报告</th>
                  </tr>
                </thead>

                <tr align="center" v-for="(item, index) in middleCheckData" :key="index">
                  <td>{{ item.processName }}</td>
                  <td>{{ item.rowNum }}</td>
                  <td>{{ item.position }}</td>
                  <td>{{ item.sampleDesc }}</td>
                  <td style="white-space: nowrap">{{ item.sampleTime }}</td>
                  <td>{{ item.analysisName }}</td>
                  <td>
                    <view style="width: 100px">{{ item.itemName }}</view>
                  </td>
                  <td>{{ item.itemValue }}</td>
                  <td>
                    <block v-if="item.attachmentsEntities && item.attachmentsEntities.length">
                      <view v-for="file in item.attachmentsEntities" :key="file.id"
                        style="min-width: 150px; color: #2e5cf6" @click="readFile(item, file.url)">
                        {{ file.name }}
                      </view>
                    </block>
                    <text style="color: #ccc" v-else>无报告</text>
                  </td>
                </tr>
                <!-- </tbody> -->
              </table>
            </scroll-view>
          </view>
          <view class="table-container" v-if="finalCheckData.length" style="margin-top: 15rpx">
            <scroll-view scroll-x scroll-y class="th-table">
              <table class="analysis-table">
                <thead class="sticky_top">
                  <tr>
                    <th colspan="9">终检检验报告</th>
                  </tr>
                  <tr>
                    <th>工序</th>
                    <th>报检次序</th>
                    <th>取样位置</th>
                    <th style="white-space: nowrap">取样时机描述</th>
                    <th>取样时机</th>
                    <th>分析手段</th>
                    <th>指标名称</th>
                    <th>实测值</th>
                    <th>报告</th>
                  </tr>
                </thead>
                <tbody>
                  <tr align="center" v-for="(item, index) in finalCheckData" :key="index">
                    <td>{{ item.processName }}</td>
                    <td>{{ item.rowNum }}</td>
                    <td>{{ item.position }}</td>
                    <td>{{ item.sampleDesc }}</td>
                    <td style="white-space: nowrap">{{ item.sampleTime }}</td>
                    <td>{{ item.analysisName }}</td>
                    <td>
                      <view style="width: 100px">{{ item.itemName }}</view>
                    </td>
                    <td>{{ item.itemValue }}</td>
                    <td>
                      <block v-if="item.attachmentsEntities && item.attachmentsEntities.length">
                        <view v-for="file in item.attachmentsEntities" :key="file.id"
                          style="min-width: 150px; color: #2e5cf6" @click="readFile(item, file.url)">
                          {{ file.name }}
                        </view>
                      </block>
                      <text style="color: #ccc" v-else>无报告</text>
                    </td>
                  </tr>
                </tbody>
              </table>
            </scroll-view>
          </view>
        </th-card>
				<th-card id="reportView6" title="报告图表" v-if="form.compoundFlag != 1">
					<view class="chart-container" v-for="(chart, index) in chartList" :key="index">
						<echarts :option="chart.chartOptions" style="height: 400px"></echarts>
					</view>
				</th-card>
				<th-card id="reportView7" title="附件">
					<view class="table-container">
						<table class="analysis-table">
							<tbody>
								<tr>
									<th>附件名称</th>
									<th>附件描述</th>
								</tr>
								<block v-if="fileList.length">
									<tr align="center" v-for="( item, index ) in  fileList " :key="index"
										@click="previewFile(item.fileUrl)">
										<td>{{ item.fileName }}</td>
										<td>{{ item.remark }}</td>
									</tr>
								</block>
								<block v-else>
									<tr align="center">
										<td :colspan="2">暂无数据</td>
									</tr>
								</block>
							</tbody>
						</table>
					</view>
				</th-card>
				<th-card id="reportView8" title="评审结论" v-if="form.compoundFlag != 1">
					<th-form labelWidth="100px">
						<th-form-item label="是否结题">
							<text v-if="form.status != 1">{{ form.completeFlag ? '是' : '否'
							}}</text>
							<wd-radio-group v-else v-model="form.completeFlag" inline @change="radioChange">
								<wd-radio :value="0">否</wd-radio>
								<wd-radio :value="1">是</wd-radio>
							</wd-radio-group>
						</th-form-item>
						<th-form-item label="评审结果" v-if="form.completeFlag == 0 || form.status == 2">
							<wd-picker v-model="form.rdFlag" :columns="rdFlags"
								:disabled="[1, 2].includes(form.status) || form.taskAllStatus != 1"
								style="background-color: transparent;padding:0;" class="diabledStyle" />
						</th-form-item>
						<th-form-item label="回复" v-if="form.status == 2">
							<wd-textarea type="textarea" v-model="form.reply" auto-height placeholder=" "
								style="width: 100%" disabled class="diabledStyle"></wd-textarea>
						</th-form-item>
						<th-form-item label="结论" v-if="form.status == 2">
							<wd-textarea type="textarea" v-model="form.conclusion" auto-height placeholder=" "
								style="width: 100%" disabled class="diabledStyle"></wd-textarea>
						</th-form-item>

						<th-form-item label="需求反馈方式" v-if="form.status == 2">
							<wd-picker v-model="form.replyFlag" :columns="replyFlags" disabled
								style="background-color: transparent;padding:0;" class="diabledStyle" placeholder=" " />
						</th-form-item>
						<!-- <th-form-item label="评审意见">
							<wd-textarea auto-height v-model="form.advise" placeholder=" " style="width: 100%" disabled
								class="diabledStyle"></wd-textarea>
						</th-form-item> -->
					</th-form>

					<view v-if="form.completeFlag == 1 && form.status == 2 && form.compoundFlag != 1">
						<view class="viewLabel"><text>评审附件</text></view>
						<view class="table-container">
							<table class="analysis-table">
								<tbody>
									<tr>
										<th>附件名称</th>
										<th>附件描述</th>
									</tr>
									<block v-if="reviewFileList.length">
										<tr align="center" v-for="(item, index) in reviewFileList" :key="index"
											@click="previewFile(item.fileUrl)">
											<td>{{ item.fileName }}</td>
											<td>{{ item.remark }}</td>
										</tr>
									</block>
									<block v-else>
										<tr align="center">
											<td :colspan="2">暂无数据</td>
										</tr>
									</block>
								</tbody>
							</table>
						</view>
					</view>
					<th-form labelWidth="100px">
						<th-form-item v-for="item in form.userList.filter(item => item.documentsPostName != '参会人员')"
							:label="item.documentsPostName">
							<wd-img :width="200" :height="100" :src="item.userUrl" @click="preview(item.userUrl)" />
						</th-form-item>
					</th-form>
					<th-form labelWidth="100px">
						<th-form-item
							v-for="prop in form.userList.filter(prop => prop.documentsPostName == '参会人员' && prop.userUrl)"
							:label="prop.documentsPostName">
							<wd-img :width="200" :height="100" :src="prop.userUrl" @click="preview(prop.userUrl)" />
						</th-form-item>
					</th-form>
					<view v-if="form.status == 2">
						<view class="viewLabel"><text>评审意见</text></view>
						<view class="table-container">
							<table class="analysis-table">
								<tbody>
									<tr>
										<th>评审人</th>
										<th>评审意见</th>
									</tr>
									<block v-if="form.adviseList.length">
										<tr align="center" v-for="(item, index) in form.adviseList" :key="index">
											<td>{{ item.username }}</td>
											<td>{{ item.advise }}</td>
										</tr>
									</block>
									<block v-else>
										<tr align="center">
											<td :colspan="2">暂无数据</td>
										</tr>
									</block>
								</tbody>
							</table>
						</view>
					</view>
				</th-card>
				<th-card id="reportView8" title="评审结论" v-else>
					<th-form labelWidth="100px">
						<th-form-item label="是否结题">
							<text v-if="form.status != 1">{{ form.completeFlag ? '是' : '否'
							}}</text>
							<wd-radio-group v-else v-model="form.completeFlag" inline>
								<wd-radio :value="0">否</wd-radio>
								<wd-radio :value="1">是</wd-radio>
							</wd-radio-group>
						</th-form-item>
						<th-form-item label="需求反馈方式"
							v-if="form.completeFlag == 1 && (form.status == 1 || form.status == 2) && form.showSelect == 1">
							<wd-picker v-model="form.replyFlag" :columns="replyFlags" :disabled="[2].includes(form.status) || form.taskAllStatus != 1 || ![3, null].includes(form.replyNeed)"
								style="background-color: transparent;padding:0;" class="diabledStyle" />
						</th-form-item>

						<th-form-item label="结论">
							<wd-textarea type="textarea" v-model="form.conclusion" auto-height placeholder=" "
								style="width: 100%" :disabled="[1, 2].includes(form.status) || form.taskAllStatus != 1"
								class="diabledStyle"></wd-textarea>
						</th-form-item>
					</th-form>
				</th-card>
				<th-card id="reportView10" title="审核信息" v-if="[1, 2, 3].includes(form.status)">
					<view class="row-list">
						<view class="row" v-if="form.id && form.taskId">
							<!-- <view class="label">审核意见</view> -->
							<view class="value">
								<view class="mb2 mt2">
									<h5>审核意见</h5>
								</view>
								<wd-textarea type="textarea" v-model="comment" rows="6" placeholder="请输入审核意见"
									style="border: 1px solid #f7f7f7"></wd-textarea>
							</view>
						</view>
						<view>
							<flowTable ref="flowDetailsTableRef" :processInstanceId="form.instanceId"></flowTable>
						</view>
					</view>
				</th-card>
			</scroll-view>
		</view>
		<view class="flow-btn-fixed" v-if="form.taskAllStatus == '1'">
			<view class="btn_group" style="width: 100%" v-if="form.id && form.instanceId">
				<view class="btn danger" @click="oncomplete(1)" v-if="form.id && form.taskId && form.status == 1">
					<image src="../../../static/reject.png" class="btn-icon"></image>
					拒绝
				</view>
				<view class="btn primary" @click="oncomplete(0)" v-if="form.id && form.taskId && form.status == 1">
					<image src="../../../static/tongyi.png" class="btn-icon"></image>
					同意
				</view>
				<view class="btn primary" @click="onRevokeShow()" v-if="form.id && form.status == 1">
					<image src="../../../static/rovoke.png" class="btn-icon"></image>
					撤回
				</view>
				<view class="btn primary" @click="onReviveShow()"
					v-if="form.id && [2].includes(form.status) && form.taskAllStatus == 1">
					<image src="../../../static/rovoke1.png" class="btn-icon"></image>
					弃审
				</view>

			</view>
			<view class="btn_group" style="width: 100%" v-else>
				<view class="btn danger" @click="oncomplete(1)" v-if="form.id && form.status == 1">
					<image src="../../../static/reject.png" class="btn-icon"></image>
					拒绝
				</view>
				<view class="btn primary" @click="oncomplete(0)" v-if="form.id && form.status == 1">
					<image src="../../../static/tongyi.png" class="btn-icon"></image>
					同意
				</view>
				<view class="btn primary" @click="onRevokeShow()" v-if="form.id && form.status == 1">
					<image src="../../../static/rovoke.png" class="btn-icon"></image>
					撤回
				</view>
				<view class="btn primary" @click="onReviveShow()"
					v-if="form.id && [2].includes(form.status) && form.taskAllStatus == 1">
					<image src="../../../static/rovoke1.png" class="btn-icon"></image>
					弃审
				</view>
			</view>
		</view>
		<wd-popup v-model="revokeShow" position="bottom" @close="handleClose">
			<view style="display: flex; flex-direction: column; height: 100%">
				<wd-textarea v-model="revokeComment" placeholder="请填写撤回原因" no-border prop="revokeComment"
					class="reovke-textarea" />
				<view class="flow-btn-fixed">
					<view class="btn_group" style="width: 100%">
						<view class="btn danger" @click="handleClose">取消</view>
						<view class="btn primary" @click="onRevoke">撤回</view>
					</view>
				</view>
			</view>
		</wd-popup>
		<wd-popup v-model="reviveShow" position="bottom" @close="handleClose">
			<view style="display: flex; flex-direction: column; height: 100%">
				<wd-textarea v-model="reviveComment" placeholder="请填写弃审原因" no-border prop="reviveComment"
					class="reovke-textarea" />
				<view class="flow-btn-fixed">
					<view class="btn_group" style="width: 100%">
						<view class="btn danger" @click="handleClose">取消</view>
						<view class="btn primary" @click="onCancelApprover">弃审</view>
					</view>
				</view>
			</view>
		</wd-popup>
	</view>
</template>
<script lang="ts" setup>
import { request } from '@/utils/request';
import { useSetting } from '@/stores/setting';
import echarts from '@/components/echarts.vue';
import { reportInfo } from '@/service/pm-assay';
import {
  getRdTaskDetail,
  getObj,
  getSchemeInfoByRecord,
  getDosageByRecord,
  getExperimentRecord,
  getQcMiddleReport,
  complete,
  revokeProcess,
  abandon,
} from '@/service/pm-report';
import { getPageByTask, resultByRecords } from '@/service/pm-record';
import { pieOption, lineOption, barOption } from './echartType';
import { totalProportion } from '../experiment/utils/index';

import ExperimnetStepPreview from '../experiment/components/ExperimnetStepPreview.vue';
import ExperimnetStepTablePreview from './components/ExperimnetStepTablePreview.vue';
import { useUserStore } from '@/stores/user';

const setting = useSetting();

const statusBar = ref(130);
const hideTitleNav = ref(false);
const showCatalogues = ref(false);
const currentNode = ref(1);
const nodeNum = ref(1);
const showOpenMenu = ref(true);
const preScrollTop = ref(0);
const openMenuBottom = ref(300);
const openMenuTouch = ref({
  startY: 0,
});
const userStore: any = useUserStore();
const middleCheckData = ref([]);
const finalCheckData = ref([]);
const showMoreDemand = ref(false);
const switchAction = ref(false);

const heightStyle = computed(() => {
  return `calc(100vh - ${statusBar.value}px)`;
});


const checkPremiss = (k) => {
    return userStore.userInfos.authBtnList.some((v: string) => v === k);
};

const typeList: Array<TypeOption> = [
  {
    label: '折线图',
    code: 'line',
    type: 0,
  },
  {
    label: '柱状图',
    code: 'bar',
    type: 1,
  },
  {
    label: '饼图',
    code: 'pie',
    type: 2,
  },
];

const replyFlags = ref([
	{
		label: '总经理确认后反馈',
		value: 2
	},
	{
		label: '直接反馈',
		value: 1
	},
	{
		label: '不反馈',
		value: 0
	},
])

const rdFlags = ref([
	{
		label: '修正实验方案',
		value: 0
	},
	{
		label: '通过',
		value: 1
	},
	{
		label: '重新实验',
		value: 2
	},
	{
		label: '调整合成路径',
		value: 3
	},
	{
		label: '终止任务',
		value: 4
	},
])

const taskType = ref([
  {
    label: '来样检验',
    value: 2,
  },
  {
    label: '新品资料收集合成路线',
    value: 3,
  },
  {
    label: '直接取样检测',
    value: 30,
  },
  {
    label: '调查问卷',
    value: 4,
  },
  {
    label: '复配稀释',
    value: 6,
  },
  {
    label: '其他',
    value: 9,
  },
  {
    label: '研发任务',
    value: 10,
  },
]);

const catalogues = ref([
  {
    name: '基础信息',
    value: 1,
  },
  {
    name: '需求指标',
    value: 2,
  },
  {
    name: '用料及配比',
    value: 3,
  },
  {
    name: '工艺流程及参数',
    value: 4,
  },
  {
    name: '检验结论',
    value: 5,
  },
  {
    name: '报告图表',
    value: 6,
  },
  {
    name: '附件',
    value: 7,
  },
  {
    name: '评审结论',
    value: 8,
  },
  // {
  // 	name: '结题附件',
  // 	value: 9
  // },
  {
    name: '审核信息',
    value: 9,
  },
]);

// 提交表单数据
const form = reactive({
	replyFlag: 2,
	userList: [],
	reportResultList: [],
	adviseList: []
});

const chartList = ref([]);

const recordOutList = ref([]);
const materialList = ref([]);
const fileList = ref([]);
const reviewFileList = ref([]);
onLoad((options) => {
  const id = options.id;
  init({
    id: id,
  });
});

const goBack = () => {
  uni.navigateBack();
};

const readFile = (item, url) => {
  if (item.tempFilePath) {
    uni.openDocument({
      filePath: item.tempFilePath,
      showMenu: false,
    });
  } else {
    uni.showLoading({
      title: '加载中',
    });
    uni.downloadFile({
      url,
      success(res) {
        item.tempFilePath = res.tempFilePath;
        uni.hideLoading();
        uni.openDocument({
          filePath: res.tempFilePath,
          showMenu: false,
          success() {
            console.log('打开文档成功');
          },
        });
      },
    });
  }
};

const radioChange = (e) => {
  if (e.value) {
    rdFlags.value = [
      {
        label: '通过',
        value: 1,
      },
    ];
  } else {
    rdFlags.value = [
      {
        label: '修正实验方案',
        value: 0,
      },
      {
        label: '重新实验',
        value: 2,
      },
      {
        label: '调整合成路径',
        value: 3,
      },
      {
        label: '终止任务',
        value: 4,
      },
    ];
  }
};

const onClickTab = (e) => {
  // this.childrenNode = ""
  if (nodeNum.value === e.value && nodeNum.value !== currentNode.value) {
    nodeNum.value = '';
    nextTick(() => {
      nodeNum.value = e.value;
    });
  } else {
    nodeNum.value = e.value;
  }
  currentNode.value = e.value;
  setTimeout(() => {
    currentNode.value = e.value;
    setTabs();
  }, 300);
};

const setTabs = () => {
  const query = uni.createSelectorQuery().in(this);
  catalogues.value.forEach((item) => {
    query
      .select(`#reportView${item.value} .content`)
      .boundingClientRect((data) => {
        item.nodeHeight = data.height + 10;
      })
      .exec();
  });
};

const toggleCatalogues = () => {
  showCatalogues.value = !showCatalogues.value;
  if (!showCatalogues.value) {
    setTimeout(() => {
      showOpenMenu.value = true;
    }, 260);
  } else {
    showOpenMenu.value = false;
  }
  setTimeout(() => {
    setTabs();
  }, 1000);
};
// const onSchemeInited = (e) => {
//     setTabs()
// }
// const onNotesInited = (e) => {
//     setTabs()
// }

const isNotNum = (val: string | null | number): boolean => {
  if (typeof val === 'string' && !isNaN(Number(val))) {
    return val.indexOf('.') < 0 && val.indexOf('0') == 0;
  } else {
    return isNaN(Number(val));
  }
};

const transferAndToFixed = (num, length = 0) => {
  const str = num.toFixed(length).toString();
  const reg = str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(\d{3})+$)/g;
  return str.replace(reg, '$1,');
};

const maxPlanDosage = (density: number, proportion: number, maxValue: number) => {
  if (isNotNum(density)) return 0;
  if (isNotNum(maxValue)) return 0;
  if (isNotNum(proportion)) return 0;

  let maxNum = 0;
  //密度（g/ml） * 占比 * 最大搅拌量（ml）
  maxNum =
    transferAndToFixed(Number(density), 4) *
    transferAndToFixed(Number(proportion), 4) *
    transferAndToFixed(Number(maxValue), 4);
  return unifyNumber(transferAndToFixed(maxNum / 100, 4));
};

const minPlanDosage = (density: number, proportion: number, minValue: number) => {
  if (isNotNum(density)) return 0;
  if (isNotNum(minValue)) return 0;
  if (isNotNum(proportion)) return 0;
  let minNum = 0;
  //密度（g/ml） *  占比 * 最小搅拌量（ml）
  minNum =
    transferAndToFixed(Number(density), 4) *
    transferAndToFixed(Number(proportion), 4) *
    transferAndToFixed(Number(minValue), 4);
  return unifyNumber(transferAndToFixed(minNum / 100, 4));
};

const onViewScroll = (e) => {
  if (e.detail.scrollTop < 40) {
    hideTitleNav.value = false;
  }
  if (preScrollTop.value && e.detail.scrollTop > 60) {
    if (e.detail.scrollTop - preScrollTop.value < -60) {
      hideTitleNav.value = false;
      preScrollTop.value = e.detail.scrollTop;
    } else if (e.detail.scrollTop - preScrollTop.value > 60) {
      hideTitleNav.value = true;
      preScrollTop.value = e.detail.scrollTop;
    }
  } else {
    preScrollTop.value = e.detail.scrollTop;
  }
  if (e.detail.scrollTop <= catalogues.value[0].nodeHeight - 12) {
    currentNode.value = 1;
    return;
  }
  let aboveHeight = 0;
  for (let i = 0; i < catalogues.value.length; i++) {
    const _curr = catalogues.value[i];
    aboveHeight += _curr.nodeHeight;
    if (
      e.detail.scrollTop >= aboveHeight &&
      e.detail.scrollTop <= aboveHeight + (catalogues.value[i + 1]?.nodeHeight || 0) - 12
    ) {
      currentNode.value = _curr.value + 1;
      // catalogues.value.map(item => item.openChildren = false)
      // // 判断当前类型有子节点且没有展开则自动展开
      // const currentNode = catalogues.value[i + 1]
      // if (currentNode && currentNode.children && currentNode.children.length && !currentNode.openChildren) {
      //     currentNode.openChildren = true
      // }
      break;
    }
  }
};

const onTouchOpenMenu = (e) => {
  openMenuTouch.value.startY = e.touches[0].clientY;
  openMenuTouch.value.bottom = openMenuBottom.value;
};

const flowDetailsTableRef = ref();
const init = (params) => {
  uni.showLoading();
  getObj(params)
    .then((res) => {
      res.data.deviceList = (res.data.equipmenList && res.data.equipmenList) || [];
      Object.assign(form, res.data);

      fileList.value = res.data.fileList || [];
      reviewFileList.value = res.data.reviewFileList || [];

      // getBjReportResultList(res.data.checkReportId);

      addInit(res.data.pid);

      renderChart(res.data.chartList);
      nextTick(() => {
        flowDetailsTableRef.value?.getFlowDetails();
      });
    })
    .finally(() => {
      uni.stopPullDownRefresh();
      uni.hideLoading();
    });
};

const isImage = (url: string) => {
  if (!url) return '';
  const suffix = url.replace(/.*\./, '') || url;
  return ['jpg', 'jpeg', 'png', 'gif', 'svg', 'JPG', 'JPEG', 'PNG', 'GIF', 'SVG', 'WebP'].includes(
    suffix,
  );
};

const previewFile = (url) => {
  if (!url) return;
  if (isImage(url)) {
    preview(url);
  } else {
    previewFileHandle(url);
  }
};

const preview = (url) => {
  if (!url) return;
  uni.previewImage({
    urls: [url],
  });
};

const previewFileHandle = (file) => {
  uni.navigateTo({
    url: '/pages/pm/preview-online?url=' + file,
  });
};
const previewWeb = (url) => {
  uni.navigateTo({
    url: '/pages/pm/preview-online?url=' + url + '&isWeb=1',
  });
};

const addInit = (id) => {
  getDosageByRecordList(id);
  getSchemeInfoByRecord(id).then((res) => {
    if (res.code === 0) {
      form.purpose = res.data.purpose;
      form.compoundFlag = res.data.compoundFlag
      if (res.data.taskId) {
        getProjectInfo({ id: res.data.taskId, recordId: id });
      }

      if (form.compoundFlag == 1) {
        catalogues.value = catalogues.value.filter(item => !['报告图表'].includes((item.name)))
        replyFlags.value = [
          {
            label: '总经理确认后反馈',
            value: 2
          },
          {
            label: '直接反馈',
            value: 1
          },
        ]
      }
    }
  })
  getExperimentRecord(id).then((res) => {
    if (res.code === 0) {
      form.stepList = res.data.stepList.map((item) => {
        if (item.processName === '中控') {
          item.sampletimeList = [];
          item.checkList = [];
          item.paramList.map((v) => {
            if (v.mcFlag == 1) {
              item.sampletimeList.push(v);
            } else {
              item.checkList.push({
                analysisId: v.analysisId,
                analysisName: v.analysisName,
                itemName: v.paramName,
                status: v.status,
              });
            }
          });
        }

        return item;
      });

      recordOutList.value =
        res.data.dosageList
          ?.map((item) => {
            item.recallFlag = res.data.recallFlag;
            return item;
          })
          .filter((item) => item.type) || [];
      getProcessPageByTask(res.data.id);
    }
  });

  // 检验结论
  getResultByRecords(id);
  // getStepTable(id)
};

//请求中控检验数据
const getResultByRecords = (recordId: string) => {
  console.log(recordId);
  resultByRecords({ recordId })
    .then((res) => {
      if (res.code === 0) {
        if (res.data && res.data.length > 0) {
          middleCheckData.value = res.data.filter((item) => item.type == 0);
          finalCheckData.value = res.data.filter((item) => item.type == 1);
        }
      }
    })
    .catch((error) => {
      const err = error.msg || error.error || error;
    });
};

/**
 * 实验记录查看
 */
const tableStepList = ref([]);
const getStepTable = async (record) => {
  if (!record) return;
  try {
    const { data } = await request({
      url: `/pm/experimentRecord/stepTable/${record}`,
      method: 'get',
    });

    tableStepList.value = data;
  } catch (error) {
    console.log(error);
    // options.onError(error as any);
  }
};

const getProcessPageByTask = function (id: string) {
  getPageByTask({ pid: id, size: 999 }).then((res) => {
    if (res.code === 0) {
      if (form.stepList) {
        form.stepList.map((item) => {
          if (item.putIntoFlag && !item.dosageList?.length) {
            item.dosageList = [{ invName: null, unit: null }];
          }
          item.undraggable = true;

          // if (item.processName === '终检') {
          // 	const zj = res.data.records.find(item => item.type === 1)
          // 	if (zj) {
          // 		item.bgId = zj.id
          // 		item.pid = zj.pid
          // 	}

          // }

          item.inspectionList = res.data.records.filter((v) => v.pid === item.id && v.id) || [];
        });
        form.stepList = form.stepList;
      }
    }
  });
};

const unifyNumber = (num, len = 6) => {
	if (num === '') return ''
	let handleNum = parseFloat(num)
	let isToFixed = handleNum.toString().includes('.') && handleNum.toString().split('.')[1].length > len
	if (isToFixed) {
		return handleNum.toFixed(len)
	} else {
		return handleNum
	}
}

const getDosageByRecordList = (recordId) => {
  getDosageByRecord(recordId).then((res) => {
    if (res.code === 0) {
      if (!res.data) return;
      materialList.value = res.data.map((item) => {
        if (item.planNum) {
          item.planNum = unifyNumber(item.planNum);
        }
        if (item.realNum) {
          item.realNum = unifyNumber(item.realNum);
        }
        return item;
      });
      // materialList.value = res.data;
    }
  });
};

const getProjectInfo = function (params) {
	getRdTaskDetail(params).then((res) => {
		if (res.code === 0) {
			console.log(res.data)
			form.projectHeadName = res.data.rdProjectUserEntity.filter(item => item.userType == 2) || [];
			form.rdProjectUserEntity = res.data.rdProjectUserEntity.filter(item => item.userType == 0) || [];
			form.rdDemandStandardEntity = res.data.rdDemandStandardEntity || []
			form.taskAllStatus = res.data.taskAllStatus
			// form.projectHeadName = res.data.projectHeadName;
			// form.technologyHead = res.data.technologyHead;
			// form.technologyHeadName = res.data.technologyHeadName;
			// form.rdProjectUserEntity = res.data.rdProjectUserEntity;
			form.petitionName = res.data.petitionName
			form.replyNeed = res.data.replyNeed;
			if (!form.rdDemandStandardEntity.length) {
				catalogues.value = catalogues.value.filter(item => !['需求指标'].includes((item.name)))
			}

			if (res.data.replyNeed != 3 && res.data.replyNeed != null) {
				form.replyFlag = res.data.replyNeed;
				form.showSelect = 0;
			} else {
				form.showSelect = 1;
				form.replyFlag = 2 //默认总经理确认后反馈
			}

      if (form.compoundFlag == 1) {
        form.rdDemandEntityInvStd = res.data.invStd || res.data.rdDemandEntity.invStd || '';
        form.rdDemandEntityInvName = res.data.invName || res.data.rdDemandEntity.invName || '';
      }

      if (form.rdDemandStandardEntity != null && form.rdDemandStandardEntity.length > 0) {
        resultByRecords(params).then((res) => {
          if (res.code === 0) {
            if (res.data && res.data.length > 0) {
              finalCheckData.value = res.data.filter((item) => item.type == 1);
              // state.finalCheckTableData = finalCheckData.value;
              console.log('需求指标' + form.rdDemandStandardEntity);
              if (form.rdDemandStandardEntity != null && form.rdDemandStandardEntity.length > 0) {
                form.rdDemandStandardEntity.forEach((item) => {
                  let values = finalCheckData.value.filter(
                    (check) => item.standardName == check.itemName,
                  );
                  if (values != null && values.length > 0) {
                    item.checkValue = values[values.length - 1].itemValue;
                  }
                });
              }
            }
          }
        });
      }
    }
  });
};

const getBjReportResultList = (id) => {
  if (!id) return;
  reportInfo('qcMiddleReport', { id }).then((res) => {
    if (res.code === 0) {
      if (res.data.qcMiddleReportsList) {
        form.reportResultList = [];
        res.data.qcMiddleReportsList.map((item) => {
          item.itemDTOS &&
            item.itemDTOS.map((p) => {
              if (!res.data.resultFlag) {
                p.standardValuePm = '';
              }

              form.reportResultList.push(p);
            });
        });
      }
    }
  });

  // getQcMiddleReport(id)
  // 	.then((res) => {
  // 		if (res.code === 0) {
  // 			if (res.data.qcMiddleReportsList) {
  // 				res.data.qcMiddleReportsList.map(item => {
  // 					item.itemDTOS && item.itemDTOS.map(p => {
  // 						if (!res.data.resultFlag) {
  // 							p.standardValuePm = ""
  // 						}
  // 						form.reportResultList.push(p)
  // 					})
  // 				})
  // 			}

  // 		}
  // 	})
};

// 渲染图表数据
const renderChart = (list) => {
  if (!list || !list.length) return;
  const arr = list.map((item) => {
    let styleObj = {
      xDateLine: false,
      yDateLine: false,
      line: {
        smooth: false,
        disabled: true,
      },
      bar: {
        barWidth: null,
        barGap: 30,
        disabled: true,
      },
      pie: {
        centerLeft: 50,
        centerTop: 50,
        innerCircle: 40,
        outerCircle: 70,
      },
    };
    item.paramList.forEach((p: { styleList: any[] }) => {
      p.styleList &&
        p.styleList.forEach((i: { style: string }) => {
          if (i.style) {
            const style = JSON.parse(i.style);
            styleObj = {
              ...styleObj,
              ...style,
            };
          }
        });
      item.style = styleObj;
    });
    return item;
  });

  initEChart(arr);
};

function matchStringBeforeChar(str, char) {
  const regex = new RegExp();
  return str.match(regex);
}

const viewFileName = (name) => {
  if (!name) return '-';
  return name.substring(0, name.lastIndexOf('.'));
};

const initEChart = function (list) {
  chartList.value = list.map((item, index) => {
    const chartOptions = JSON.parse(JSON.stringify(defaultOption(item)));
    chartOptions.id = 'echarts' + index;
    return { chartOptions };
  });
};

/**
 * 获取echart图表类型
 */
const getEChartType = (type) => {
  const eType = typeList.find((item) => item.type === type);
  if (eType) return eType;
};

function defaultOption(params) {
  let option = {};
  const echartOption = getEChartType(params.type);
  switch (echartOption.code) {
    case 'line':
      option = lineECharts(params);
      break;
    case 'bar':
      option = barECharts(params);
      break;
    case 'pie':
      option = pieECharts(params);
      break;

    default:
      break;
  }
  return {
    title: {
      top: 0,
      text: params.chartName,
      left: 'center',
    },
    toolbox: {
      feature: {
        magicType: {
          show: false,
          type: ['stack', 'tiled'],
        },
        saveAsImage: {},
      },
    },
    ...option,
  };
}
const colors = [
  '#5470C6',
  '#91CC75',
  '#EE6666',
  '#1E90FF',
  '#00FA9A',
  '#3CB371',
  '#FFF8DC',
  '#FAF0E6',
  '#CD5C5C',
  '#DC143C',
  '#FF1493',
  '#4B0082',
  '#9932CC',
  '#BA55D3',
  '#6495ED',
  '#B0C4DE',
];
const lineECharts = (param) => {
  const line = lineOption;
  const legends = param.paramList.map((item: any) => item.paramName + ` (${item.unit})`);
  let xData = [];
  let series = [];
  let yData = [];
  param.paramList.forEach((item: any, index) => {
    item.valueList.forEach((p: any) => {
      if (xData.every((t) => t !== p.x)) {
        xData.push(p.x);
      }
    });
    let indexSub = index % 2;
    let colorIndex = index % 16;
    let indexdiv = index / 2;
    let offsetNum = indexdiv * 60;
    yData.push({
      type: 'value',
      name: item.paramName,
      position: indexSub == 0 ? 'left' : 'right',
      offset: offsetNum,
      alignTicks: true,
      axisLine: {
        show: true,
        lineStyle: {
          color: colors[index],
        },
      },
      axisLabel: {
        show: true,
        formatter: '{value} ' + (item.unit != null && item.unit != '' ? item.unit : ''),
      },
    });
    series.push({
      name: item.paramName + ` (${item.unit})`,
      smooth: param.style.line.smooth,
      type: 'line',
      yAxisIndex: index,
      data: item.valueList.map((p: any) => p.y),
    });
  });

  line.dataZoom[0].show = param.style.xDateLine;
  line.dataZoom[1].disabled = param.style.line.disabled;
  line.dataZoom[2].show = param.style.yDateLine;
  line.legend.data = legends;
  line.yAxis = yData;
  line.xAxis.data = xData.filter((i) => i);
  line.series = series;
  return line;
};

const pieECharts = (param) => {
	const pie = pieOption;
	pie.series[0].data = param.paramList.map((item: { valueList: any[]; paramName: any }) => {
		let total: any = 0;
		item.valueList.forEach((item: any) => {
			total += Number(item.value)
			total = unifyNumber(total, 4)
		});
		return {
			name: item.paramName,
			value: total,
		};
	});

  pie.series[0].center = [param.style.pie.centerLeft + '%', param.style.pie.centerTop + '%'];
  pie.series[0].radius = [param.style.pie.innerCircle + '%', param.style.pie.outerCircle + '%'];

  return pie;
};

const barECharts = (param) => {
  const bar = barOption;
  const legends = param.paramList.map((item: any) => item.paramName + ` (${item.unit})`);

  let xData = [];
  let series = [];
  let yData = [];
  param.paramList.forEach((item: any, index) => {
    item.valueList.forEach((p: any) => {
      if (xData.every((t) => t !== p.x)) {
        xData.push(p.x);
      }
    });
    let indexSub = index % 2;
    let colorIndex = index % 16;
    let indexdiv = index / 2;
    let offsetNum = indexdiv * 60;
    yData.push({
      type: 'value',
      name: item.paramName,
      position: indexSub == 0 ? 'left' : 'right',
      offset: offsetNum,
      alignTicks: true,
      axisLine: {
        show: true,
        lineStyle: {
          color: colors[index],
        },
      },
      axisLabel: {
        show: true,
        formatter: '{value} ' + (item.unit != null && item.unit != '' ? item.unit : ''),
      },
    });
    series.push({
      name: item.paramName + ` (${item.unit})`,
      type: 'bar',
      barGap: param.style.bar.barGap + '%',
      yAxisIndex: index,
      barWidth: param.style.bar.barWidth,
      emphasis: {
        focus: 'series',
      },
      label: {
        show: true,
        position: 'top',
      },
      data: item.valueList.map((p: { y: any }) => p.y),
    });
  });

  bar.dataZoom[0].show = param.style.xDateLine;
  bar.dataZoom[1].disabled = param.style.bar.disabled;
  bar.dataZoom[2].show = param.style.yDateLine;
  bar.legend.data = legends;
  bar.xAxis.data = xData.filter((i) => i);
  bar.yAxis = yData;
  bar.series = series;
  return bar;
};

// 审核信息
const comment = ref('');
const oncomplete = (type) => {
  if (type == '1' && !comment.value) {
    uni.showToast({
      title: '请填写审核意见',
      icon: 'none',
      mask: true,
    });
    return;
  }

  if (!form.completeFlag && form.completeFlag !== 0 && form.compoundFlag != 1) {
    uni.showToast({
      title: '请选择是否结题',
      icon: 'none',
      mask: true,
    });
    return;
  }

	// if (!form.rdFlag && form.rdFlag !== 0 && form.compoundFlag != 1) {
	// 	uni.showToast({
	// 		title: '请选择评审结果',
	// 		icon: 'none',
	// 		mask: true,
	// 	});
	// 	return;
	// }

	// 复配 && 反馈没选 && 需求单评审反馈没选
	// if (form.compoundFlag == 1 && form.replyFlag == null && form.showSelect == 1) {
	// 	uni.showToast({
	// 		title: '需求反馈方式必选',
	// 		icon: 'none',
	// 		mask: true,
	// 	});
	// 	return;
	// }


  const params = {
    taskId: form.taskId,
    comment: comment.value,
    id: form.id,
    approve: type == 0 ? true : false,
    completeFlag: form.completeFlag,
    rdFlag: form.rdFlag,
    replyFlag: form.replyFlag,
  };
  uni.showLoading({
    mask: true,
  });
  complete(params, form.id)
    .then((res) => {
      if (res.code == 0) {
        uni.showToast({
          title: '单据审核成功',
          icon: 'none',
          mask: true,
        });
        init({
          id: form.id,
        });
        uni.$emit('refresh');

      } else {
        uni.showToast({
          mask: true,
          title: `单据审核失败，失败原因：${res.msg}`,
          icon: 'none',
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};

// 撤回
const revokeComment = ref('');
const revokeShow = ref(false);

const onRevokeShow = () => {
  revokeShow.value = true;
};
const handleClose = () => {
  revokeShow.value = false;
  reviveShow.value = false;
};
const onRevoke = () => {
  uni.showModal({
    title: '提示',
    content: '是否撤回该单据',
    showCancel: true,
    success: ({ confirm, cancel }) => {
      if (cancel) {
        return;
      }
      uni.showLoading({
        mask: true,
      });
      revokeProcess({
        id: form.id,
        instanceId: form.instanceId,
        comment: revokeComment.value,
      })
        .then((res) => {
          if (res.code == 0) {
            uni.showToast({
              mask: true,
              title: `单据${form.schemeNo}撤回成功`,
              icon: 'none',
            });
            handleClose();
            init({ id: form.id });
          } else {
            uni.showToast({
              mask: true,
              title: `单据${form.schemeNo}撤回失败，失败原因：${res.msg}`,
              icon: 'none',
            });
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
  });
};

// 弃审
const reviveComment = ref('');
const reviveShow = ref(false);

const onReviveShow = () => {
  reviveShow.value = true;
};

const onCancelApprover = () => {
  uni.showModal({
    title: '提示',
    content: '是否弃审该单据',
    showCancel: true,
    success: ({ confirm, cancel }) => {
      if (cancel) {
        return;
      }
      uni.showLoading({
        mask: true,
      });
      abandon({
        id: form.id,
        comment: revokeComment.value,
      })
        .then((res) => {
          if (res.code == 0) {
            uni.showToast({
              mask: true,
              title: `单据${form.schemeNo}弃审成功`,
              icon: 'none',
            });
            handleClose();
            init({ id: form.id });
            // nextTick(() => {
            //   flowDetailsTableRef.value.getFlowDetails();
            // });
          } else {
            uni.showToast({
              mask: true,
              title: `单据${form.schemeNo}弃审失败，失败原因：${res.msg}`,
              icon: 'none',
            });
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
  });
};


</script>
<style lang="scss" scoped>
$color-primary: #409eff;

@import '../experiment/components/table';

.task-custom {
  transition: 0.32s;

  &.hide {
    top: -150rpx !important;
    color: rgb(0 0 0 / 0%);
  }
}

.scroll-container {
  // height: calc(100vh - 0rpx);
  display: flex;
  transition: 0.32s;

  .viewTable {
    flex: auto;

    :deep() {
      .content {
        width: calc(100% - 100px);
      }
    }
  }

  .left-container {
    flex-shrink: 0;
    width: 240rpx;
    margin-right: 12rpx;
    overflow: hidden;
    background-color: #fff;
    transition: 0.32s;

    &.hide {
      width: 0;
      margin-right: 0;
    }

    .left {
      width: 240rpx;
    }

    .item {
      white-space: nowrap;
      border-bottom: 1rpx solid #f3f3f3;

      .item_text {
        padding: 24rpx 6rpx;
        font-size: 1rem;
        font-weight: bold;
        border-left: 6rpx solid #fff;
        transition: 0.26s;

        &.no_data {
          color: #dedede;
        }
      }

      &.active {
        .item_text {
          color: $color-primary;
          border-left: 6rpx solid $color-primary;
        }
      }

      //     .childrens {
      //         font-size: 0.8125rem;
      //         font-weight: initial;

      //         .c_item {
      //             display: flex;
      //             align-items: center;
      //             height: 96rpx;
      //             margin-left: 12rpx;
      //             padding: 12rpx 12rpx;
      //             border-bottom: 1rpx solid #f7f7f7;

      //             >text {
      //                 white-space: pre-wrap;
      //                 overflow: hidden;
      //                 text-overflow: ellipsis;
      //                 -webkit-line-clamp: 2;
      //                 -webkit-box-orient: vertical;
      //                 display: -webkit-box;
      //             }

      //             &.active {
      //                 color: $color-primary;
      //             }

      //             &:last-child {
      //                 border-bottom: none;
      //             }
      //         }
      //     }
      // }

      // .uni-collapse-item {
      //     /deep/.uni-collapse-item--border {
      //         border-bottom: 0;
      //     }
      // }
    }

    .flex-1 {
      flex: 1;
    }

    .scroll-view {
      overflow: hidden;
      transition: 0.32s;

      :deep(.form-item) {
        min-width: 520rpx;
      }

      .title {
        display: flex;
        align-items: center;
        justify-content: space-around;
        padding: 12rpx;
        margin-top: 32rpx;
        margin-bottom: 12rpx;
        font-size: 1.125rem;
        font-weight: bold;
        color: #007aff;

        text {
          margin: 0 12rpx;
        }

        .line {
          flex: 1;

          // border: 4rpx solid rgba($color: #007aff, $alpha: 0.6);
          height: 6rpx;
          margin: 0 12rpx;
          background-color: rgba($color: #007aff, $alpha: 60%);
        }
      }
    }
  }

  .container {
    // min-height: calc(100vh - 100rpx - 24px);
    min-height: 50vh;
    background-color: #fff;
  }

  .diabledStyle {
    :deep() {

      .wd-picker__value,
      .wd-textarea__inner {
        color: #262626;
      }

      .wd-picker__cell {
        padding: 0;
      }
    }
  }

  .toggle {
    position: sticky;
    height: 80rpx;
    padding: 24rpx 12rpx 12rpx;
    overflow: hidden;

    // z-index: 2;
    // top: 0;
    color: #666;
    white-space: nowrap;
    background-color: #fff;
  }

  .open {
    position: fixed;
    z-index: -1;
    width: 40rpx;
    padding: 32rpx 0;
    line-height: 1;
    color: #fff;
    text-align: center;
    background-color: rgba($color: #000, $alpha: 50%);
    border-top-right-radius: 12rpx;
    border-bottom-right-radius: 12rpx;
    opacity: 0;
    transition: 0.26s;

    &.show {
      z-index: 999;
      opacity: 1;
    }
  }

  .toggle {
    position: sticky;
    height: 80rpx;
    padding: 24rpx 12rpx 12rpx;
    overflow: hidden;

    // z-index: 2;
    // top: 0;
    color: #666;
    white-space: nowrap;
    background-color: #fff;
  }

  .open {
    position: fixed;
    z-index: -1;
    width: 40rpx;
    padding: 32rpx 0;
    line-height: 1;
    color: #fff;
    text-align: center;
    background-color: rgba($color: #000, $alpha: 50%);
    border-top-right-radius: 12rpx;
    border-bottom-right-radius: 12rpx;
    opacity: 0;
    transition: 0.26s;

    &.show {
      z-index: 999;
      opacity: 1;
    }
  }

  .craft-row-img {
    width: 80rpx;
    height: 80rpx;
  }

  .chart-container {
    padding-top: 24rpx;
  }

  .viewLabel {
    position: relative;
    flex: 1;
    flex-shrink: 0;
    width: 3.75rem;
    min-width: 16.875rem;
    padding: 0.5625rem 0;
    margin: 0 0.75rem;
    font-size: 0.8125rem;
    line-height: 1;
    color: #666;
  }

  .exportModel {
    width: 100%;
    margin-top: 10rpx;
    font-size: 28rpx;
    color: #409eff;
    text-align: center;
  }

  .viewLabel~.table-container {
    margin: 0 0.75rem;
  }

  :deep() {
    .wd-textarea {
      &::after {
        display: none !important;
      }
    }
  }

  .chart-container {
    padding-top: 24rpx;
  }

  .viewLabel {
    position: relative;
    flex: 1;
    flex-shrink: 0;
    width: 3.75rem;
    min-width: 16.875rem;
    padding: 0.5625rem 0;
    margin: 0 0.75rem;
    font-size: 0.8125rem;
    line-height: 1;
    color: #666;
  }

  .viewLabel~.table-container {
    margin: 0 0.75rem;
  }

  :deep() {
    .wd-textarea {
      &::after {
        display: none !important;
      }
    }
  }
}

.flow-btn-fixed {
  width: 100%;
  background-color: white;
  border-top: 1px solid #f2f2f1;
}

.btn_group {
  display: flex;
  justify-content: space-between;

  // margin: 0rpx 0 20rpx;
  // border-bottom: 1px solid #f2f2f1;

  .btn {
    display: flex;

    // width: 49%;
    flex: 1;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    // height: 40px;
    min-height: 40px;
    padding: 10rpx 0;
    font-size: 24rpx;
    color: black;

    // background-color: white !important;
    background-color: #dbecff !important;
    border-left: 1px solid #f7f7f7;
    border-radius: 0 !important;

    // color: white;
    border-radius: 6rpx;

    .btn-icon {
      width: 40rpx;
      height: 40rpx;
      margin-bottom: 8rpx;
    }
  }

  .danger {
    background-color: #f56c6c;
  }

  .primary {
    background-color: #409eff;
  }
}

.th-table {
  max-height: 500px;

  .sticky_top {
    position: sticky;
    top: 0;
    z-index: 9;

    th::before {
      position: absolute;
      top: -1px;
      left: 0;
      width: 100%;
      height: 1px;
      content: '';
      background: #dedede;
    }
  }
}
</style>
